import 'package:flutter/material.dart';
import '../theme/app_theme.dart';

/**
 * 笔记列表视图组件
 * 显示笔记列表，支持搜索、排序和选择
 */
class NoteListView extends StatefulWidget {
  final String? selectedFolderId;
  final String? searchQuery;
  final Function(String)? onNoteSelected;
  final Function()? onNewNote;

  const NoteListView({
    Key? key,
    this.selectedFolderId,
    this.searchQuery,
    this.onNoteSelected,
    this.onNewNote,
  }) : super(key: key);

  @override
  State<NoteListView> createState() => _NoteListViewState();
}

class _NoteListViewState extends State<NoteListView> {
  String _selectedNoteId = '';
  String _sortBy = 'updated'; // updated, created, title
  bool _sortAscending = false;

  // 模拟笔记数据
  final List<NoteModel> _notes = [
    NoteModel(
      id: '1',
      title: '新笔记',
      content: '# 开始写作\n\n这是一个新的笔记，你可以在这里记录你的想法...',
      folderId: 'folder1',
      createdAt: DateTime.now().subtract(const Duration(hours: 2)),
      updatedAt: DateTime.now().subtract(const Duration(minutes: 30)),
      tags: ['工作', '重要'],
    ),
    NoteModel(
      id: '2',
      title: '会议记录',
      content: '## 项目进度会议\n\n- 完成了用户界面设计\n- 开始后端开发\n- 下周进行测试',
      folderId: 'folder1',
      createdAt: DateTime.now().subtract(const Duration(days: 1)),
      updatedAt: DateTime.now().subtract(const Duration(hours: 1)),
      tags: ['会议', '项目'],
    ),
    NoteModel(
      id: '3',
      title: '学习笔记',
      content: '# Flutter 开发笔记\n\n## Widget 生命周期\n\n1. createState()\n2. initState()\n3. build()',
      folderId: 'folder2',
      createdAt: DateTime.now().subtract(const Duration(days: 3)),
      updatedAt: DateTime.now().subtract(const Duration(days: 1)),
      tags: ['学习', 'Flutter'],
    ),
    NoteModel(
      id: '4',
      title: '待办事项',
      content: '## 今日待办\n\n- [ ] 完成代码审查\n- [ ] 更新文档\n- [x] 参加会议',
      folderId: 'folder1',
      createdAt: DateTime.now().subtract(const Duration(days: 2)),
      updatedAt: DateTime.now().subtract(const Duration(hours: 3)),
      tags: ['待办', '工作'],
    ),
  ];

  /**
   * 获取过滤后的笔记列表
   */
  List<NoteModel> get _filteredNotes {
    var notes = _notes.where((note) {
      // 文件夹过滤
      if (widget.selectedFolderId != null && 
          widget.selectedFolderId!.isNotEmpty &&
          note.folderId != widget.selectedFolderId) {
        return false;
      }
      
      // 搜索过滤
      if (widget.searchQuery != null && widget.searchQuery!.isNotEmpty) {
        final query = widget.searchQuery!.toLowerCase();
        return note.title.toLowerCase().contains(query) ||
               note.content.toLowerCase().contains(query) ||
               note.tags.any((tag) => tag.toLowerCase().contains(query));
      }
      
      return true;
    }).toList();

    // 排序
    notes.sort((a, b) {
      int comparison = 0;
      switch (_sortBy) {
        case 'title':
          comparison = a.title.compareTo(b.title);
          break;
        case 'created':
          comparison = a.createdAt.compareTo(b.createdAt);
          break;
        case 'updated':
        default:
          comparison = a.updatedAt.compareTo(b.updatedAt);
          break;
      }
      return _sortAscending ? comparison : -comparison;
    });

    return notes;
  }

  @override
  Widget build(BuildContext context) {
    final filteredNotes = _filteredNotes;

    return Container(
      decoration: const BoxDecoration(
        color: AppTheme.backgroundSecondary,
        border: Border(
          right: BorderSide(color: AppTheme.borderLight, width: 1),
        ),
      ),
      child: Column(
        children: [
          _buildHeader(),
          _buildSortBar(),
          Expanded(
            child: filteredNotes.isEmpty
                ? _buildEmptyState()
                : _buildNotesList(filteredNotes),
          ),
        ],
      ),
    );
  }

  /**
   * 构建头部区域
   */
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: AppTheme.backgroundPrimary,
        border: Border(
          bottom: BorderSide(color: AppTheme.borderLight, width: 1),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: Text(
              widget.selectedFolderId != null ? '文件夹笔记' : '所有笔记',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: AppTheme.textPrimary,
              ),
            ),
          ),
          IconButton(
            onPressed: widget.onNewNote,
            icon: const Icon(Icons.add, size: 20),
            style: IconButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.all(8),
              minimumSize: const Size(32, 32),
            ),
            tooltip: '新建笔记',
          ),
        ],
      ),
    );
  }

  /**
   * 构建排序栏
   */
  Widget _buildSortBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: const BoxDecoration(
        color: AppTheme.backgroundPrimary,
        border: Border(
          bottom: BorderSide(color: AppTheme.borderLight, width: 1),
        ),
      ),
      child: Row(
        children: [
          const Text(
            '排序：',
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: AppTheme.textSecondary,
            ),
          ),
          const SizedBox(width: 8),
          _buildSortButton('updated', '最近更新'),
          const SizedBox(width: 8),
          _buildSortButton('created', '创建时间'),
          const SizedBox(width: 8),
          _buildSortButton('title', '标题'),
          const Spacer(),
          IconButton(
            onPressed: () {
              setState(() {
                _sortAscending = !_sortAscending;
              });
            },
            icon: Icon(
              _sortAscending ? Icons.arrow_upward : Icons.arrow_downward,
              size: 16,
            ),
            style: IconButton.styleFrom(
              padding: const EdgeInsets.all(4),
              minimumSize: const Size(24, 24),
            ),
            tooltip: _sortAscending ? '升序' : '降序',
          ),
        ],
      ),
    );
  }

  /**
   * 构建排序按钮
   */
  Widget _buildSortButton(String sortType, String label) {
    final isSelected = _sortBy == sortType;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _sortBy = sortType;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: isSelected ? AppTheme.primaryColor : Colors.transparent,
          borderRadius: BorderRadius.circular(4),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w500,
            color: isSelected ? Colors.white : AppTheme.textSecondary,
          ),
        ),
      ),
    );
  }

  /**
   * 构建笔记列表
   */
  Widget _buildNotesList(List<NoteModel> notes) {
    return ListView.builder(
      padding: const EdgeInsets.all(8),
      itemCount: notes.length,
      itemBuilder: (context, index) {
        final note = notes[index];
        final isSelected = _selectedNoteId == note.id;
        
        return Container(
          margin: const EdgeInsets.only(bottom: 8),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () {
                setState(() {
                  _selectedNoteId = note.id;
                });
                widget.onNoteSelected?.call(note.id);
              },
              borderRadius: BorderRadius.circular(8),
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: isSelected 
                      ? AppTheme.noteItemSelected 
                      : AppTheme.noteItemBackground,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: isSelected 
                        ? AppTheme.primaryColor 
                        : AppTheme.noteItemBorder,
                    width: isSelected ? 2 : 1,
                  ),
                  boxShadow: isSelected ? const [
                    BoxShadow(
                      color: AppTheme.shadowLight,
                      offset: Offset(0, 1),
                      blurRadius: 2,
                      spreadRadius: 0,
                    ),
                  ] : null,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                      note.title,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                        color: AppTheme.textPrimary,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    
                    // 内容预览
                    Text(
                      _getContentPreview(note.content),
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                        color: AppTheme.textSecondary,
                        height: 1.4,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8),
                    
                    // 标签和时间
                    Row(
                      children: [
                        // 标签
                        if (note.tags.isNotEmpty) ...[
                          Expanded(
                            child: Wrap(
                              spacing: 4,
                              children: note.tags.take(2).map((tag) {
                                return Container(
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 6,
                                    vertical: 2,
                                  ),
                                  decoration: BoxDecoration(
                                    color: AppTheme.backgroundTertiary,
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: Text(
                                    tag,
                                    style: const TextStyle(
                                      fontSize: 10,
                                      fontWeight: FontWeight.w500,
                                      color: AppTheme.textTertiary,
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ] else
                          const Spacer(),
                        
                        // 更新时间
                        Text(
                          _formatTime(note.updatedAt),
                          style: const TextStyle(
                            fontSize: 10,
                            fontWeight: FontWeight.w500,
                            color: AppTheme.textTertiary,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /**
   * 构建空状态
   */
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.note_outlined,
            size: 64,
            color: AppTheme.textTertiary,
          ),
          const SizedBox(height: 16),
          Text(
            widget.searchQuery?.isNotEmpty == true
                ? '没有找到相关笔记'
                : '还没有笔记',
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: AppTheme.textSecondary,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            widget.searchQuery?.isNotEmpty == true
                ? '尝试使用其他关键词搜索'
                : '点击右上角的 + 按钮创建第一个笔记',
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
              color: AppTheme.textSecondary,
            ),
          ),
          if (widget.onNewNote != null) ...[
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: widget.onNewNote,
              icon: const Icon(Icons.add, size: 18),
              label: const Text('创建笔记'),
            ),
          ],
        ],
      ),
    );
  }

  /**
   * 获取内容预览
   */
  String _getContentPreview(String content) {
    // 移除 Markdown 标记
    String preview = content
        .replaceAll(RegExp(r'#{1,6}\s+'), '') // 移除标题标记
        .replaceAll(RegExp(r'\*\*(.+?)\*\*'), r'$1') // 移除粗体标记
        .replaceAll(RegExp(r'\*(.+?)\*'), r'$1') // 移除斜体标记
        .replaceAll(RegExp(r'`(.+?)`'), r'$1') // 移除代码标记
        .replaceAll(RegExp(r'\[(.+?)\]\(.+?\)'), r'$1') // 移除链接标记
        .replaceAll(RegExp(r'- \[[ x]\] '), '') // 移除任务列表标记
        .replaceAll(RegExp(r'^- ', multiLine: true), '') // 移除列表标记
        .trim();
    
    return preview.isEmpty ? '空笔记' : preview;
  }

  /**
   * 格式化时间显示
   */
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);
    
    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${dateTime.month}/${dateTime.day}';
    }
  }
}

/**
 * 笔记数据模型
 */
class NoteModel {
  final String id;
  final String title;
  final String content;
  final String? folderId;
  final DateTime createdAt;
  final DateTime updatedAt;
  final List<String> tags;

  const NoteModel({
    required this.id,
    required this.title,
    required this.content,
    this.folderId,
    required this.createdAt,
    required this.updatedAt,
    this.tags = const [],
  });
}